package com.hurst

class ContractorController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def timesheets = {
        def name = params.contractorName.replaceAll("-", " ")
        Contractor contractor = Contractor.findByNameIlike(name)

        if(contractor){
            render view: 'timesheets', model:[contractor: contractor]
        } else{
            render 'no can haz'
        }
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [contractorInstanceList: Contractor.list(params), contractorInstanceTotal: Contractor.count()]
    }

    def create = {
        def contractorInstance = new Contractor()
        contractorInstance.properties = params
        return [contractorInstance: contractorInstance]
    }

    def save = {
        println params
        def contractorInstance = new Contractor(params)

        if(contractorInstance.manager){
            Manager.get(contractorInstance.manager.id).addToContractors(contractorInstance)
        }
        if (contractorInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'contractor.label', default: 'Contractor'), contractorInstance.id])}"
            redirect(action: "list")
        }
        else {
            render(view: "create", model: [contractorInstance: contractorInstance])
        }
    }


    def delete = {
        def contractorInstance = Contractor.get(params.id)
        if (contractorInstance) {
            try {
                contractorInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'contractor.label', default: 'Contractor'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'contractor.label', default: 'Contractor'), params.id])}"
                redirect(action: "list")
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contractor.label', default: 'Contractor'), params.id])}"
            redirect(action: "list")
        }
    }
}
